package com.study.crypto.basic.general.spring.handler;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.ImmutableMap;
import com.study.crypto.basic.dto.api.ReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常处理
 * @author Songjin
 * @since 2022-11-01 13:30
 */
@Slf4j
public class GeneralDefaultHandlerExceptionResolver {

    /**
     * 统一参数校验异常
     *
     * @param e 参数校验异常
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, HttpMessageNotReadableException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ReturnResult<Map<String, String>> resovleMethodArgumentNotValidException(Exception e) {
        log.error("异常堆栈", e);
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            BindingResult errorResult = ex.getBindingResult();
            Map<String, String> jsonError = new HashMap<>(3);
            for (FieldError fieldError : errorResult.getFieldErrors()) {
                jsonError.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return ReturnResult.build(HttpStatus.BAD_REQUEST.value(), "参数校验失败", jsonError);
        } else {
            HttpMessageNotReadableException ex = (HttpMessageNotReadableException) e;
            Throwable cause = ex.getCause();
            if (cause instanceof JsonMappingException) {
                JsonMappingException realEx = (JsonMappingException) cause;
                List<JsonMappingException.Reference> references = realEx.getPath();
                List<String> fieldNames = new ArrayList<>();
                references.forEach(ref -> fieldNames.add(ref.getFieldName()));
                String path = StringUtils.join(fieldNames, ".");
                String theField = fieldNames.get(fieldNames.size() - 1);
                Map<String, String> jsonError = ImmutableMap.of(path, theField + "参数类型错误");
                return ReturnResult.build(HttpStatus.BAD_REQUEST.value(), "参数校验失败", jsonError);
            }
            throw ex;
        }
    }

    /**
     * 统一异常处理。若其他异常处理器未能处理某异常，该方法进行默认处理并返回
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> resovleGlobalException(Exception e) {
        log.error("异常堆栈", e);
        String message = StringUtils.defaultString(e.getMessage(), "服务器错误");
        return ImmutableMap.<String, Object>builder()
                           .put("status", HttpStatus.INTERNAL_SERVER_ERROR.value())
                           .put("message", message)
                           .build();
    }

}
